import { map } from 'lodash-es'

import type {
  GetPositionByCodeRequest,
  GetPositionByCodeResponse
} from '/@/api/types/paas/省、市、县（区）、镇（街道办）、村全数据相关接口/通过code查询地址Types'
import { http, randomUUid } from '@/utils'

/**
 * 通过code与层级查询地址
 * @returns {Promise<GetPositionByCodeResponse>}
 * @param params
 */
export function getPositionByCode(params?: GetPositionByCodeRequest) {
  return http.get<GetPositionByCodeResponse>(
    '/paas/paasposition/getPositionByCode',
    params
  )
}

interface FieldNames {
  label?: string
  value?: string
  children?: string
  disabled?: boolean
  isLeaf?: boolean
  levelType?: number
}

export interface DefaultOptionType {
  key: string
  label: any
  value: string | number | null
  levelType: number
  children?: DefaultOptionType[]
  disabled?: boolean

  [name: string]: any
}

export const makeCascaderOptions = <T extends Recordable>(
  records: T[],
  fieldNames: FieldNames = {}
): DefaultOptionType[] => {
  return map(records, (item) => {
    const childrenData = item[fieldNames.children ?? 'children']

    return {
      key: randomUUid(),
      label: item[fieldNames.label ?? 'name'],
      value: item[fieldNames.value ?? 'id'],
      children: childrenData?.length
        ? makeCascaderOptions(childrenData)
        : undefined,
      disabled: fieldNames.disabled ?? false,
      isLeaf: fieldNames.isLeaf ?? false,
      levelType: fieldNames.levelType ?? 1,
      _props: item
    }
  })
}

export const loadAddressList = async (
  node?: DefaultOptionType,
  fieldNames: FieldNames = {}
) => {
  return makeCascaderOptions(
    await getPositionByCode({
      levelType: node?.levelType ? node.levelType + 1 : 1,
      parentCode: node?.value
    }),
    {
      label: 'name',
      value: 'code',
      ...fieldNames
    }
  )
}
